<template>
  <div class="main">
    <el-form
      class="form"
      ref="formRef"
      :model="ruleForm"
      label-position="right"
      label-width="70"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          class="form__input"
          placeholder="请输入用户名"
          v-model="ruleForm.username"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="密&emsp;码" prop="password">
        <el-input
          class="form__input"
          placeholder="请输入密码"
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="验证码" prop="verifyCode">
        <el-input
          class="form__input--code"
          placeholder="验证码"
          v-model="ruleForm.verifyCode"
          type="text"
          autocomplete="off"
          @keyup.enter="handlerLogin"
        />
        <!-- 验证码组件 -->
        <div class="code" v-html="svg" @click="Code"></div>
      </el-form-item>

      <!-- 记住密码 -->
      <label class="form__rememberBox">
        <input
          type="checkbox"
          ref="rememberBox"
          name="choose"
          v-model="checkedFlag"
          @change="isChecked"
        />
        <span>记住密码</span>
      </label>

      <!-- 登录 -->
      <el-form-item class="form__btn">
        <el-button type="primary" :loading="loading" @click="handlerLogin"
          >登录</el-button
        >
        <el-button @click="handlerRemove">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getCode } from "@/api/user";
import { ElMessage } from "element-plus";
import router from "@/router";
export default {
  name: "login",
  data() {
    return {
      checkedFlag: false, //是否记住密码
      svg: "", //svg图片
      captchaId: "", //svg图片id
      rules: {
        //验证规则
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        verifyCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
        ],
      },
      ruleForm: {
        //存储表单数据 (admin  / 123456)
        username: JSON.parse(localStorage.getItem("Form"))?.username || "",
        password: JSON.parse(localStorage.getItem("Form"))?.password || "",
        verifyCode: "",
      },
      loading: false, //正在加载
    };
  },
  mounted() {
    this.Code();
    this.checkedFlag = JSON.parse(localStorage.getItem("flag"));
  },
  methods: {
    handlerRemove() {
      console.log(router.getRoutes());
    },
    //记住密码
    isChecked() {
      //是否保存账号密码
      if (this.checkedFlag) {
        localStorage.setItem("Form", JSON.stringify(this.ruleForm));
      } else {
        localStorage.removeItem("Form");
      }
    },
    //获取验证码
    async Code() {
      let result = await getCode();
      this.svg = result.data;
      this.captchaId = result.captchaId;
    },
    //登录
    handlerLogin() {
      //为了让登陆前验证,需要在组件实例上获取校验方法;需要在组件上定义一个modle
      const params = {
        ...this.ruleForm,
        captchaId: this.captchaId,
      };
      //验证表单
      this.$refs.formRef.validate(async (flag) => {
        if (!flag) {
          return;
        }
        try {
          this.loading = true;
          const data = await this.$store.dispatch("user/login", params);
          // 移动到路由全局前置守卫调用
          // await this.$store.dispatch("user/getInfo");
          if (data === "ok") {
            ElMessage({
              message: "登录成功",
              type: "success",
              duration: 1000,
              // 消息关闭时的回调
              onClose: () => {
                this.loading = false;
                //跳转页面
                const redirect =
                  this.$route.query.redirect || "/dashboard/console";
                this.$router.replace(redirect);
              },
            });
            //记住密码
            this.checkedFlag = this.$refs.rememberBox.checked;
            this.$store.dispatch("user/changFlag", this.checkedFlag);
          } else {
            this.loading = false;
            this.ruleForm.verifyCode = "";
            this.Code();
          }
        } catch (error) {
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.main {
  height: 100%;
  background-color: skyblue;
  position: relative;
}

.form {
  width: 400px;
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
  box-sizing: border-box;
  border-radius: 5px;

  &__input {
    width: 300px;

    &--code {
      width: 100px;
    }
  }
  &__rememberBox {
    display: flex;
    width: 300px;
    height: 30px;
    align-items: center;
    padding-left: 20px;
    > input {
      width: 18px;
      height: 18px;
      margin-right: 10px;
    }
  }

  &__btn {
    width: 300px;
    display: flex;

    .el-button {
      margin-left: auto;
    }
  }
}

.code {
  width: 150px;
  height: 40px;
  margin-left: 50px;
  background-color: #ccc;

  ::v-deep(svg) {
    width: 100%;
    height: 40px;
  }
}
</style>
